const message = require('../model/returnMessage');
const busboy = require('busboy');
const path = require('path');
const md5 = require('../utils/md5');
const fs = require('fs');
const { server } = require('../config/config.default');
const {
  isAccountHasPortrait,
  setAccountHasPortrait,
  setAccountInfo,
  setPassword,
  getAccountInfoByUsername,
  getAccountInfo,
} = require('../model/account');

module.exports.setPortrait = async (req, res, next) => {
  let bb = busboy({ headers: req.headers });
  bb.on('file', (name, file, info) => {
    if (!/^image\/[(png)|(jpeg)]$/.test(info.mimeType)) {
      res.status(401).json('.png/.jpg/.jpeg picture needed.');
    }
    try {
      const saveTo = path.join('./public/portrait', req.body.username + '.png');
      file.pipe(fs.createWriteStream(saveTo));
    } catch (error) {
      res.status(500).json('Internal server error.');
    }
  });

  bb.on('close', () => {
    res.writeHead(200, { Connection: 'close' });
    res.end('文件上传成功');
  });
};

module.exports.setPortraitInfo = async (req, res, next) => {
  setAccountHasPortrait(req.body.username, req.body.username + '.png').then(
    (r) => {
      res
        .status(200)
        .json(message({ username: req.body.username }, 'Portrait created.'));
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error'));
    }
  );
};

module.exports.getPortrait = async (req, res, next) => {
  isAccountHasPortrait(req.params.username).then(
    (r) => {
      if (r[0].has_portrait === '0') {
        res.status(200).json(
          message({
            url: server.baseURL + '/portrait/' + 'default.png',
          })
        );
      } else {
        res.status(200).json(
          message({
            url: server.baseURL + '/portrait/' + r[0].has_portrait,
          })
        );
      }
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error.'));
    }
  );
};

module.exports.setAccountInfo = async (req, res, next) => {
  const { age, username, description } = req.body;
  setAccountInfo({ age, username, description }).then(
    (r) => {
      res
        .status(201)
        .json(message({ username, age, description }, 'Information created.'));
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error.'));
    }
  );
};

module.exports.getAccountInfo = async (req, res, next) => {
  getAccountInfo(req.params.username).then(
    (r) => {
      res.status(200).json(
        message(
          {
            username: req.params.username,
            age: r[0].age,
            description: r[0].description,
          },
          'Information returned.'
        )
      );
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error.'));
    }
  );
};

module.exports.setPassword = async (req, res, next) => {
  getAccountInfoByUsername(req.body.username).then(
    (r) => {
      let password = r[0].password;
      if (password !== req.body.password) {
        res.status(400).json(message({}, 'Password error.'));
      } else {
        setPassword({
          username: req.body.username,
          password: md5(req.new_password),
        }).then(
          (_r) => {
            res
              .status(200)
              .json(
                message({ username: req.body.username }, 'Password changed.')
              );
          },
          (_e) => {
            res.status(500).json(message({}, 'Internal server error'));
          }
        );
      }
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error.'));
    }
  );
};
